package com.xdf.whiteaccount.aop;

import com.xdf.whiteaccount.dao.DyeFabricPlanMapper;
import com.xdf.whiteaccount.entity.*;
import com.xdf.whiteaccount.enums.PriceStandard;
import com.xdf.whiteaccount.enums.ResponseEnum;
import com.xdf.whiteaccount.service.CallService;
import com.xdf.whiteaccount.service.DyeProductInfoService;
import com.xdf.whiteaccount.service.DyeSpecificationService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import java.math.BigDecimal;
import java.util.Date;
import java.util.Optional;

/**
 * @program: white-account
 * @description:
 * @author: 张柯
 * @create: 2021-06-23 17:03
 **/
@Slf4j
@Component
@Aspect
public class DyeFabricPlanAspect extends AbstractAop {
    @Autowired
    private CallService callService;
    @Autowired
    private DyeProductInfoService dyeProductInfoService;
    @Autowired
    private DyeSpecificationService dyeSpecificationService;
    @Autowired
    private DyeFabricPlanMapper planMapper;

    @Pointcut("execution(* com.xdf.whiteaccount.service.DyeFabricPlanService.insert*(..))")
    public void insert() {
    }

    @Pointcut("execution(* com.xdf.whiteaccount.service.DyeFabricPlanService.update*(..))")
    public void update() {
    }

    @Pointcut("execution(* com.xdf.whiteaccount.service.DyeFabricPlanService.cancelByPrimaryKey(..))")
    public void delete() {
    }

    /**
     * 新增编号
     *
     * @param joinPoint
     */
    @Before("insert()")
    @Transactional(rollbackFor = Exception.class)
    public void beforeInsert(JoinPoint joinPoint) throws Exception {
        Object para = getParam1(joinPoint);
        if (para instanceof DyeFabricPlan) {
            DyeFabricPlan plan = (DyeFabricPlan) para;
            PriceStandard e = PriceStandard.match(plan.getPriceStandard());
            // 2023年11月30日 10:08:21 新增代码，忽略计价标准的判断
            e = null;
            //Assert.state(e != null, "计价标准必须输入！");
            if (e == PriceStandard.EXPRESS_METER) {
                //  公式记米默认记米标记勾选
                plan.setMeterCounter(1);
            } else {
                //  否则米克系数无法输入
                plan.setMeterCounter(0);
                plan.setRate(null);
            }
            plan.setCreateUserId(getLoginUserId());
            plan.setPlanCode(callService.dyeFabricPlanCodeGen());
            plan.setId(null);
            plan.setState(1);
//            plan.setUpload(0);
            plan.setMarkFinished(false);
            if (plan.getPlanDate() == null) {
                plan.setPlanDate(new Date());
            }
            if (plan.getMeterCounter() == null) {
                plan.setMeterCounter(0);
            }
            //  当前基础资料是否有色布品名,没有则添加
            if (StringUtils.isNotEmpty(plan.getProductName())) {
                DyeProductInfo info = DyeProductInfo.builder().productName(plan.getProductName()).build();
                if (CollectionUtils.isEmpty(dyeProductInfoService.listQuery(info))) {
                    dyeProductInfoService.insertSelective(info);
                }
            }
            //  当前基础资料是否有色布规格,没有则添加
            if (StringUtils.isNotEmpty(plan.getMaterialSpecification())) {
                DyeSpecification info = DyeSpecification.builder().specName(plan.getMaterialSpecification()).build();
                if (CollectionUtils.isEmpty(dyeSpecificationService.listQuery(info))) {
                    dyeSpecificationService.insertSelective(info);
                }
            }
        }
    }

    /**
     * 修改
     *
     * @param joinPoint
     */
    @Before("update()")
    public void beforeUpdate(JoinPoint joinPoint) {
        Object para = getParam1(joinPoint);
        if (para instanceof DyeFabricPlan) {
            DyeFabricPlan plan = (DyeFabricPlan) para;
            Assert.state(plan.getId() != null, "没有主键,无法修改！");
            DyeFabricPlan prev = planMapper.selectByPrimaryKey(plan.getId());
            Assert.state(!Optional.ofNullable(prev).map(DyeFabricPlan::getIsAudit).orElse(false), ResponseEnum.IS_AUDIT.getName());
            Assert.state(!Optional.ofNullable(prev).map(DyeFabricPlan::getMarkFinished).orElse(false), "已完工不允许修改!");
            PriceStandard e = PriceStandard.match(plan.getPriceStandard());
            if (e != null) {
                if (e == PriceStandard.EXPRESS_METER) {
                    //  公式记米默认记米标记勾选
                    plan.setMeterCounter(1);
                } else {
                    //  否则米克系数无法输入
                    plan.setMeterCounter(0);
                    plan.setRate(BigDecimal.ZERO);
                }
            }
            if (Optional.ofNullable(plan).map(DyeFabricPlan::getMeterCounter).orElse(0) == 0) {
                //  记米没有勾选,那么清空米克系数
                plan.setMeterCounter(0);
                plan.setRate(BigDecimal.ZERO);
            }
//            plan.setUpload(0);
        }
    }

    /**
     * 删除前事件
     *
     * @param joinPoint
     * @throws Exception
     */
    @Before("delete()")
    @Transactional(rollbackFor = Exception.class)
    public void beforeCancel(JoinPoint joinPoint) throws Exception {
        Object param = getParam1(joinPoint);
        if (param instanceof Long) {
            DyeFabricPlan record = planMapper.selectByPrimaryKey((Long) param);
            Assert.notNull(record, ResponseEnum.NO_ORDER.getName());
            Assert.state(!Optional.ofNullable(record).map(DyeFabricPlan::getIsAudit).orElse(false), ResponseEnum.IS_AUDIT.getName());
            Assert.state(1 == record.getState(), ResponseEnum.CANCEL_ORDER.getName());
            Assert.state(!Optional.ofNullable(record).map(DyeFabricPlan::getMarkFinished).orElse(false), "已完工不允许作废!");
        }
    }
}